package ICM.client;

import java.awt.*;
import java.awt.event.*;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Observable;
import java.util.Observer;
import java.util.Vector;

import javax.annotation.processing.Messager;
import javax.swing.*;
import javax.swing.border.*;

import common.*;

import javax.swing.table.DefaultTableModel;

public class TreatmentRequestUI extends JPanel implements ActionListener,Observer {

	private ClientUI ui;
	private Client c;
	private Request[] requests = null;
	private SystemEngineer[] syseng = null;
	private JTable table;
	private DefaultTableModel defaultModel = null;
	private Vector newRow = null;
	private String StageName = null;
	private boolean ChangeSupervisor = false;
	private JLabel lblRequest;
	private JLabel lblDepartment;
	private JLabel lblUserId;
	private JLabel lblRole;
	private JLabel lblEmail;
	private JLabel lblRequestDate;
	private JLabel lblDescription;
	private JLabel lblComments;
	private JLabel lblReasons;
	private JTextPane Description;
	private JTextPane Comments;
	private JTextPane requestID;
	private JTextPane Department;
	private JTextPane UserID;
	private JTextPane Role;
	private JTextPane Email;
	private JTextPane RequestDate;
	private JTextPane Reasons;
	private JLabel lblStatus;
	private JTextPane Status;
	private JLabel lblCurrentStage;
	private JTextPane Stage;
	private JTextPane DateOfStartTreatment;
	private JLabel lblDateOfStart;
	private JLabel lblSupervisor;
	private JComboBox SupervisorBox;
	private JButton btnSaveChanges;
	private JLabel lblUploadedDocument;
	private JTextPane Filename;
	private JButton btnDownloadFile;
	private int row;
	
	public TreatmentRequestUI(final Client c, final ClientUI ui) {
		this.c = c;
		this.ui = ui;
		c.addObserver(this);
		setLayout(null);
		int i;
		
		JLabel lblTreatmentRequest = new JLabel("Treatment Request");
		lblTreatmentRequest.setBounds(333, 24, 223, 32);
		lblTreatmentRequest.setFont(new Font("Tahoma", Font.PLAIN, 26));
		add(lblTreatmentRequest);
		// Prepare all new and active requests.
		CommandMessage msg = new CommandMessage("Get new and active requests",null);
		// requests.
		try {
			c.sendToServer(msg);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
		    Thread.sleep(200);
		} catch(InterruptedException ex) {
		    Thread.currentThread().interrupt();
		}
		
		// Get system engineers
		CommandMessage msg1 = new CommandMessage("Get system engineers",null);
		try {
			c.sendToServer(msg1);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
		    Thread.sleep(200);
		} catch(InterruptedException ex) {
		    Thread.currentThread().interrupt();
		}
		
		table = new JTable();
		table.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				JTable target = (JTable)e.getSource();
				row = target.getSelectedRow();
				lblUploadedDocument.setVisible(false);
				Filename.setVisible(false);
				btnDownloadFile.setVisible(false);
				
				if (!lblRequest.isVisible())
				{
					lblRequest.setVisible(true);
					lblDepartment.setVisible(true);
					lblUserId.setVisible(true);
					lblRole.setVisible(true);
					lblEmail.setVisible(true);
					lblRequestDate.setVisible(true);
					lblDescription.setVisible(true);
					lblComments.setVisible(true);
					requestID.setVisible(true);
					Department.setVisible(true);
					UserID.setVisible(true);
					Role.setVisible(true);
					Email.setVisible(true);
					RequestDate.setVisible(true);
					Description.setVisible(true);
					Comments.setVisible(true);
					lblStatus.setVisible(true);
					lblCurrentStage.setVisible(true);
					lblDateOfStart.setVisible(true);
					Status.setVisible(true);
					Stage.setVisible(true);
					lblSupervisor.setVisible(true);
					SupervisorBox.setVisible(true);
					DateOfStartTreatment.setVisible(true);
					btnSaveChanges.setVisible(true);
					lblReasons.setVisible(true);
					Reasons.setVisible(true);
				}
				if (requests[row].getFileInfo()!=null)
				{
					lblUploadedDocument.setVisible(true);
					Filename.setVisible(true);
					btnDownloadFile.setVisible(true);
				}
				if (table.getValueAt(row, 8)!="")
					SupervisorBox.setSelectedItem(table.getValueAt(row, 8));
				else
					SupervisorBox.setSelectedIndex(-1);
				requestID.setText(table.getValueAt(row, 0).toString());
				Department.setText(table.getValueAt(row, 1).toString());
				UserID.setText(table.getValueAt(row, 2).toString());
				Role.setText(table.getValueAt(row, 3).toString());
				Email.setText(table.getValueAt(row, 4).toString());
				RequestDate.setText(table.getValueAt(row, 5).toString());
				Description.setText(table.getValueAt(row, 6).toString());
				Comments.setText(table.getValueAt(row, 7).toString());
				if (requests[row].getDateOfStartTreatment()!=null)
					DateOfStartTreatment.setText(table.getValueAt(row, 9).toString());
				else
					DateOfStartTreatment.setText("");
				Status.setText(table.getValueAt(row, 10).toString());
				if (requests[row].getidStage()!=0)
					Stage.setText(table.getValueAt(row, 11).toString());
				else
					Stage.setText("");
				Reasons.setText(table.getValueAt(row, 12).toString());
				if (requests[row].getFileInfo()!=null)
					Filename.setText(requests[row].getFileInfo().getFilename());
				else
					Filename.setText("");
			}
		});
		table.setModel(new DefaultTableModel(
			new Object[][] {
			},
			new String[] {
				"Request ID", "Department", "User ID", "Role", "Email", "Request date", "Description", "Comments", "Supervisor ID", "Date of Start Treatment", "Status", "Current Stage", "Reasons"
			}
		));
		defaultModel = (DefaultTableModel) table.getModel();
        if (requests!=null)
		{
			for (i=0;i<requests.length;i++)
			{
				if (requests[i].getidStage()!=0)
				{
					// Get stage name
					CommandMessage msg11 = new CommandMessage("Get stage name",new Integer[] {requests[i].getidStage()});
					try {
						c.sendToServer(msg11);
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					try {
					    Thread.sleep(200);
					} catch(InterruptedException ex) {
					    Thread.currentThread().interrupt();
					}
				}
				newRow = new Vector();
				newRow.add(requests[i].getIdRequest());
		        newRow.add(requests[i].getDepartment());
		        newRow.add(requests[i].getUserID());
		        newRow.add(requests[i].getRole());
		        newRow.add(requests[i].getEmail());
		        newRow.add(requests[i].getdateRequest());
		        newRow.add(requests[i].getDescription());
		        newRow.add(requests[i].getComments());
		        if (requests[i].getidSupervisor()!=0)
		        	newRow.add(requests[i].getidSupervisor());
		        else
		        	newRow.add("");
		        newRow.add(requests[i].getDateOfStartTreatment());
		        newRow.add(requests[i].getStatus());
		        if (requests[i].getidStage()!=0)
		        	newRow.add(StageName);
		        else
		        	newRow.add("");
		        newRow.add(requests[i].getReasons());
		        defaultModel.addRow(newRow); 
		        StageName = null;
			}
		}
		JScrollPane pane = new JScrollPane(table); 
		pane.setBounds(10, 66, 913, 226);
		add(pane);
		
		JLabel lblNewRequests = new JLabel("New & Active requests:");
		lblNewRequests.setFont(new Font("Tahoma", Font.PLAIN, 14));
		lblNewRequests.setBounds(35, 64, 147, 17);
		add(lblNewRequests);
		
		lblRequest = new JLabel("Request #:");
		lblRequest.setVisible(false);
		lblRequest.setFont(new Font("Tahoma", Font.PLAIN, 14));
		lblRequest.setBounds(32, 350, 80, 17);
		add(lblRequest);
		
		lblDepartment = new JLabel("Department:");
		lblDepartment.setVisible(false);
		lblDepartment.setFont(new Font("Tahoma", Font.PLAIN, 14));
		lblDepartment.setBounds(32, 382, 80, 17);
		add(lblDepartment);
		
		lblUserId = new JLabel("User ID:");
		lblUserId.setVisible(false);
		lblUserId.setFont(new Font("Tahoma", Font.PLAIN, 14));
		lblUserId.setBounds(32, 413, 80, 17);
		add(lblUserId);
		
		lblRole = new JLabel("Role:");
		lblRole.setVisible(false);
		lblRole.setFont(new Font("Tahoma", Font.PLAIN, 14));
		lblRole.setBounds(32, 444, 80, 17);
		add(lblRole);
		
		lblEmail = new JLabel("Email:");
		lblEmail.setVisible(false);
		lblEmail.setFont(new Font("Tahoma", Font.PLAIN, 14));
		lblEmail.setBounds(32, 472, 80, 17);
		add(lblEmail);
		
		lblRequestDate = new JLabel("Request date:");
		lblRequestDate.setVisible(false);
		lblRequestDate.setFont(new Font("Tahoma", Font.PLAIN, 14));
		lblRequestDate.setBounds(32, 505, 94, 17);
		add(lblRequestDate);
		
		lblDescription = new JLabel("Description:");
		lblDescription.setVisible(false);
		lblDescription.setFont(new Font("Tahoma", Font.PLAIN, 14));
		lblDescription.setBounds(387, 379, 80, 17);
		add(lblDescription);
		
		lblComments = new JLabel("Comments:");
		lblComments.setVisible(false);
		lblComments.setFont(new Font("Tahoma", Font.PLAIN, 14));
		lblComments.setBounds(387, 472, 80, 17);
		add(lblComments);
		
		Description = new JTextPane();
		Description.setEditable(false);
		Description.setVisible(false);
		Description.setBounds(477, 350, 276, 65);
		add(Description);
		
		Comments = new JTextPane();
		Comments.setEditable(false);
		Comments.setVisible(false);
		Comments.setBounds(477, 444, 276, 65);
		add(Comments);
		
		requestID = new JTextPane();
		requestID.setEditable(false);
		requestID.setVisible(false);
		requestID.setBounds(120, 350, 208, 20);
		add(requestID);
		
		Department = new JTextPane();
		Department.setEditable(false);
		Department.setVisible(false);
		Department.setBounds(120, 379, 208, 20);
		add(Department);
		
		UserID = new JTextPane();
		UserID.setEditable(false);
		UserID.setVisible(false);
		UserID.setBounds(120, 413, 208, 20);
		add(UserID);
		
		Role = new JTextPane();
		Role.setEditable(false);
		Role.setVisible(false);
		Role.setBounds(120, 444, 208, 20);
		add(Role);
		
		Email = new JTextPane();
		Email.setEditable(false);
		Email.setVisible(false);
		Email.setBounds(120, 472, 208, 20);
		add(Email);
		
		RequestDate = new JTextPane();
		RequestDate.setEditable(false);
		RequestDate.setVisible(false);
		RequestDate.setBounds(120, 505, 208, 20);
		add(RequestDate);
		
		lblStatus = new JLabel("Status:");
		lblStatus.setVisible(false);
		lblStatus.setFont(new Font("Tahoma", Font.PLAIN, 14));
		lblStatus.setBounds(36, 571, 57, 17);
		add(lblStatus);
		
		Status = new JTextPane();
		Status.setEditable(false);
		Status.setVisible(false);
		Status.setBounds(181, 568, 147, 20);
		add(Status);
		
		lblCurrentStage = new JLabel("Current Stage:");
		lblCurrentStage.setVisible(false);
		lblCurrentStage.setFont(new Font("Tahoma", Font.PLAIN, 14));
		lblCurrentStage.setBounds(35, 599, 94, 17);
		add(lblCurrentStage);
		
		Stage = new JTextPane();
		Stage.setEditable(false);
		Stage.setVisible(false);
		Stage.setBounds(181, 596, 147, 20);
		add(Stage);
		
		DateOfStartTreatment = new JTextPane();
		DateOfStartTreatment.setEditable(false);
		DateOfStartTreatment.setVisible(false);
		DateOfStartTreatment.setBounds(181, 624, 147, 20);
		add(DateOfStartTreatment);
		
		lblDateOfStart = new JLabel("Date of start treatment:");
		lblDateOfStart.setVisible(false);
		lblDateOfStart.setFont(new Font("Tahoma", Font.PLAIN, 14));
		lblDateOfStart.setBounds(35, 627, 160, 17);
		add(lblDateOfStart);
		
		lblSupervisor = new JLabel("Supervisor:");
		lblSupervisor.setVisible(false);
		lblSupervisor.setFont(new Font("Tahoma", Font.PLAIN, 14));
		lblSupervisor.setBounds(800, 486, 80, 17);
		add(lblSupervisor);
		
		SupervisorBox = new JComboBox();
		SupervisorBox.setVisible(false);
		SupervisorBox.setBounds(800, 505, 160, 20);
		add(SupervisorBox);
		
		btnSaveChanges = new JButton("Save changes" , new ImageIcon(TreatmentRequestUI.class.getResource("/client/images/save.png")));
		btnSaveChanges.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				if (SupervisorBox.getSelectedIndex()==-1)
					ui.ShowMessageBox("Error", "Can't change supervisor" ,JOptionPane.ERROR_MESSAGE);
				else
				{
					String newSupervisor = SupervisorBox.getSelectedItem().toString();
					// Supervisor change request
					CommandMessage msg = new CommandMessage("Change supervisor",new String[] {requestID.getText(),newSupervisor});
					try {
						c.sendToServer(msg);
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					try {
					    Thread.sleep(200);
					} catch(InterruptedException ex) {
					    Thread.currentThread().interrupt();
					}
					if (ChangeSupervisor)
					{
						int row = table.getSelectedRow();
						table.setValueAt(newSupervisor, row, 8);
						CommandMessage msg1 = new CommandMessage("Get new and active requests",null);
						// requests.
						try {
							c.sendToServer(msg1);
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						try {
						    Thread.sleep(200);
						} catch(InterruptedException ex) {
						    Thread.currentThread().interrupt();
						}
						ui.ShowMessageBox("Information", "Supervisor was changed" ,JOptionPane.INFORMATION_MESSAGE);
					}
					else
						ui.ShowMessageBox("Error", "Can't change supervisor" ,JOptionPane.ERROR_MESSAGE);
				}
			}
		});
		btnSaveChanges.setVisible(false);
		btnSaveChanges.setBounds(800, 536, 160, 48);
		add(btnSaveChanges);
		
		JButton btnBack = new JButton("Back" , new ImageIcon(TreatmentRequestUI.class.getResource("/client/images/back.png")));
		btnBack.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				try {
					ui.SetContent(ClientUI.Main_Screen);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} 
			}
		});
		btnBack.setBounds(827, 622, 108, 31);
		add(btnBack);
		
		lblReasons = new JLabel("Reasons:");
		lblReasons.setVisible(false);
		lblReasons.setFont(new Font("Tahoma", Font.PLAIN, 14));
		lblReasons.setBounds(393, 571, 74, 17);
		add(lblReasons);
		
		Reasons = new JTextPane();
		Reasons.setVisible(false);
		Reasons.setBounds(477, 545, 282, 65);
		add(Reasons);
		
		lblUploadedDocument = new JLabel("Uploaded document:");
		lblUploadedDocument.setVisible(false);
		lblUploadedDocument.setBounds(800, 353, 120, 14);
		add(lblUploadedDocument);
		
		Filename = new JTextPane();
		Filename.setVisible(false);
		Filename.setBounds(800, 382, 160, 20);
		add(Filename);
		
		btnDownloadFile = new JButton("Download file");
		btnDownloadFile.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				 File file=new File(Filename.getText());
				  if (file.exists())
					    file.delete();
					    
			  FileOutputStream d = null;
			  
			  byte mybytearray[] = requests[row].getFileInfo().getFiledata();
				
				// set output stream to write file in file system
			    BufferedOutputStream bos;
				try {
					bos = new BufferedOutputStream(new FileOutputStream(file));
				    bos.write(mybytearray, 0 , mybytearray.length); //write out file
				    bos.flush(); //close buffer
				    bos.close();
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					ui.ShowMessageBox("Error", "Can't download file" ,JOptionPane.ERROR_MESSAGE);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					ui.ShowMessageBox("Error", "Can't download file" ,JOptionPane.ERROR_MESSAGE);
				}				
				ui.ShowMessageBox("Information", "File was downloaded to the application location" ,JOptionPane.INFORMATION_MESSAGE);				
			}
		});
		btnDownloadFile.setVisible(false);
		btnDownloadFile.setToolTipText("Will download the file to the application location");
		btnDownloadFile.setBounds(820, 413, 125, 32);
		add(btnDownloadFile);
		
		if (syseng!=null)
			for (i=0;i<syseng.length;i++)
				SupervisorBox.addItem(syseng[i].getId());
	}

	@Override
	public void actionPerformed(ActionEvent arg0) {
		
	}
	
	/**
	 * Handle massage from Observable class in our case Client
	 */
	@Override
	public void update(Observable arg0, Object arg1) {
		String msg = "";
		String cmd = "";
		if (arg1 instanceof TextMessage)
			msg = ((TextMessage)arg1).ToDebugMessage();
		else if (arg1 instanceof CommandMessage) {
			CommandMessage ms=(CommandMessage)arg1;
			if(ms.getCommand().equals("All new and active requests"))
					requests = (Request[]) ms.getParams()[1];
			else if(ms.getCommand().equals("Stage name"))
				StageName = (String) ms.getParams()[1];
			else if(ms.getCommand().equals("All system engineers"))
				syseng = (SystemEngineer[]) ms.getParams()[1];
			else if(ms.getCommand().equals("Supervisor changed"))
				ChangeSupervisor = Boolean.parseBoolean(ms.getParams()[1].toString());
		}
		else
			msg = arg1.toString();
	}
}